package net.zhengxinyun.performance.service.Check;

import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.api.entity.SysFile;
import net.zhengxinyun.performance.api.mapper.SysFileMapper;
import net.zhengxinyun.performance.entity.CheckEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.CheckFilter;
import net.zhengxinyun.performance.filter.IndexFilter;
import net.zhengxinyun.performance.mapper.check.CheckEntityMapper;
import net.zhengxinyun.performance.mapper.login.UserEntityMapper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.*;
import java.util.*;

/**
 * Created by hyp1202 on 2018/12/20.
 */
@Service
public class CheckServiceImpl implements CheckService {

    private CheckEntityMapper checkEntityMapper;
    private UserEntityMapper userEntityMapper;
    private SysFileMapper sysFileMapper;

    @Autowired
    public CheckServiceImpl(CheckEntityMapper checkEntityMapper, UserEntityMapper userEntityMapper, SysFileMapper sysFileMapper) {
        this.checkEntityMapper = checkEntityMapper;
        this.userEntityMapper = userEntityMapper;
        this.sysFileMapper = sysFileMapper;
    }

    @Override
    public String insert(CheckEntity entity, UserEntity userEntity) {
        //获取1-100之间的随机数
        int random = 1 + (int) (Math.random() * 99);
        //根据当前时间和随机数生成流水号。
        String mailId = DateUtils.getDateTimeString() + StringUtils.numberFormat(false, 2, 2, random);
        entity.setMailId(Long.valueOf(mailId));
        entity.setSerialNumber(0);
        entity.setStatus("0");
        entity.setSender(userEntity.getId().toString());
        int i = checkEntityMapper.insert(entity);
        if (i == 0) {
            return "发送失败，请重试";
        }
        return "发送成功";
    }

    @Override
    public String delete(CheckEntity entity) {
        int i = checkEntityMapper.deleteByMailId(entity.getMailId());
        if (i == 0) {
            return "删除失败";
        }
        return "删除成功";
    }

    @Override
    @Transactional
    public String update(CheckEntity entity) {
        if ("3".equals(entity.getStatus()) || "5".equals(entity.getStatus()) || "6".equals(entity.getStatus())) {
            return "当前状态无法修改";
        }
        CheckEntity checkEntity = new CheckEntity();
        checkEntity.setStatus("2");
        checkEntity.setMailId(entity.getMailId());
        int i = checkEntityMapper.updateByPrimaryKeySelective(entity);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "修改失败，请重试";
        }
        int a = checkEntityMapper.updateForMail(checkEntity);
        if (a == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "修改失败，请重试";
        }
        return "修改成功";
    }

    @Override
    public List<CheckFilter> query(CheckFilter filter, UserEntity userEntity) {
        if (!"admin".equals(userEntity.getUserPermissions())) {
            filter.setAddressee(userEntity.getUserDepartment());
        }
        filter.setSerialNumber(0);
        List<CheckFilter> list = checkEntityMapper.query(filter);
        return list;
    }

    @Override
    public Integer queryForCount(CheckFilter filter) {
        return checkEntityMapper.queryForCount(filter);
    }

    @Override
    @Transactional
    public String reply(CheckEntity entity, UserEntity userEntity) {
        if ("2".equals(entity.getStatus())||"3".equals(entity.getStatus()) || "5".equals(entity.getStatus()) || "6".equals(entity.getStatus())){
            return "当前状态不可回复";
        }
        if (!"agent".equals(userEntity.getUserPermissions())){
            return "当前角色不可回复";
        }
        CheckEntity checkEntity = checkEntityMapper.selectByPrimaryKey(entity.getCorrelationId());
        entity.setSerialNumber(checkEntity.getSerialNumber() + 1);
        entity.setMailId(checkEntity.getMailId());
        entity.setSender(userEntity.getId().toString());
        UserEntity user = userEntityMapper.selectByPrimaryKey(Long.valueOf(checkEntity.getSender()));
        entity.setAddressee(user.getUserDepartment());
        if (!"admin".equals(userEntity.getUserPermissions())) {
            entity.setAudit("0");
        }
        checkEntity.setStatus("2");
        int a = checkEntityMapper.updateForMail(checkEntity);
        if (a == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "回复失败，请重试";
        }
        int i = checkEntityMapper.insert(entity);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "回复失败，请重试";
        }
        return "回复成功";
    }

    @Override
    @Transactional
    public ArrayList<CheckFilter> queryForMail(CheckFilter checkFilter, UserEntity userEntity) {
        ArrayList<CheckFilter> list = checkEntityMapper.query(checkFilter);
        CheckEntity checkEntity = new CheckEntity();
        Collections.sort(list, new Comparator<CheckFilter>() {
            @Override
            public int compare(CheckFilter o1, CheckFilter o2) {
                if (o1.getSerialNumber() < o2.getSerialNumber()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        for (CheckFilter filter : list) {
            UserEntity u = userEntityMapper.selectByPrimaryKey(Long.valueOf(filter.getSender()));
            filter.setSender(u.getUserDepartment());
            checkEntity.setMailId(filter.getMailId());
        }
        if (!"admin".equals(userEntity.getUserPermissions()) && "0".equals(checkEntity.getStatus())) {
            checkEntity.setStatus("1");
            int i = checkEntityMapper.updateForMail(checkEntity);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
        }
        for (CheckFilter check : list) {
            if (StringUtils.isNotBlank(check.getFile())) {
                SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(check.getFile()));
                if (sysFile == null) {
                    continue;
                }
                check.setFileUrl(sysFile.getUrl());
                check.setFileName(sysFile.getOldName());
            }
        }
        return list;
    }

    @Override
    public String pass(CheckEntity checkEntity) {
        CheckEntity entity = new CheckEntity();
        entity.setStatus("3");
        entity.setMailId(checkEntity.getMailId());
        int i = checkEntityMapper.updateForMail(entity);
        if (i == 0) {
            return "审核失败，请重试";
        }
        return "审核成功";
    }

    @Override
    public String noPass(CheckEntity checkEntity) {
        CheckEntity entity = new CheckEntity();
        entity.setStatus("4");
        entity.setMailId(checkEntity.getMailId());
        int i = checkEntityMapper.updateForMail(entity);
        if (i == 0) {
            return "回退失败，请重试";
        }
        return "回退成功";
    }

    @Override
    @Transactional
    public String setPoint(CheckEntity checkEntity, UserEntity userEntity) {
        if (!"3".equals(checkEntity.getStatus())) {
            return "当前状态不能设置分数";
        }
        if (!"admin".equals(userEntity.getUserPermissions())) {
            return "当前账号没有权限评分";
        }
        CheckEntity entity = new CheckEntity();
        entity.setStatus("5");
        entity.setPoint(checkEntity.getPoint());
        entity.setMailId(checkEntity.getMailId());
        int i = checkEntityMapper.updateForMail(entity);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "分数设置失败";
        }
        return "设置成功";
    }

    //逾期设置
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行
    @Transactional
    public void overTime() {
        System.out.println("定时任务开始");
        String today = DateUtils.formatDate(new Date());
        List<CheckFilter> list = checkEntityMapper.queryGroupMail();
        CheckEntity entity = new CheckEntity();
        entity.setStatus("6");
        entity.setPoint(0.0);
        for (CheckFilter checkFilter:list) {
            int i = DateUtils.compareDate(today,checkFilter.getEndTime());
            if (i == 1){
                entity.setMailId(checkFilter.getMailId());
                int a = checkEntityMapper.updateForMail(entity);
                if (a == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    System.out.println("定时任务出错");
                }
            }
        }
    }

    //导出word文件
    public void build(File tmpFile, Map<String, String> contentMap, String exportFile) throws Exception {
        FileInputStream tempFileInputStream = new FileInputStream(tmpFile);
        HWPFDocument document = new HWPFDocument(tempFileInputStream);
        // 读取文本内容
        Range bodyRange = document.getRange();
        // 替换内容
        for (Map.Entry<String, String> entry : contentMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }
        //导出到文件
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        document.write(byteArrayOutputStream);
        OutputStream outputStream = new FileOutputStream(exportFile);
        outputStream.write(byteArrayOutputStream.toByteArray());
        outputStream.close();
    }

    @Override
    public String deleteForFile(CheckEntity checkEntity) {
        String id = checkEntity.getFile();
        SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(id));
        //本地配置
            String path = "D:"+sysFile.getUrl();
        //服务器配置
//        String path = "/user" + sysFile.getUrl();
        File file = new File(path);
        if (file.exists()) {
            if (!file.delete()) {
                return "删除本地图片失败";
            }
        }
        int i = sysFileMapper.deleteByPrimaryKey(Long.valueOf(id));
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "文件删除失败";
        }
        checkEntity.setFile(null);
        int a = checkEntityMapper.updateByPrimaryKeySelective(checkEntity);
        if (a == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "文件删除失败";
        }
        return "删除成功";
    }

    @Override
    public List<CheckFilter> querySumPoint(IndexFilter indexFilter) {
        String time = checkEntityMapper.queryForNewTime();
        CheckFilter checkFilter = new CheckFilter();
        checkFilter.setPoint(0.0);
        List<CheckFilter> list;
        if (StringUtils.isBlank(time)){
            list = new ArrayList<>();
            checkFilter.setType("0");
            list.add(checkFilter);
            checkFilter.setType("1");
            list.add(checkFilter);
        }else {
            time = time.substring(0,4);
            indexFilter.setDateTime(time);
            list = checkEntityMapper.querySumPoint(indexFilter);
            if (list == null || list.size() == 0){
                checkFilter.setType("0");
                list.add(checkFilter);
                checkFilter.setType("1");
                list.add(checkFilter);
            }
            if (list.size() == 1){
                list.add(new CheckFilter());
            }
        }
        return list;
    }
}
